﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using ITS.Core.Domain.Users;
using ITS.Core.ViewModel.Users;
using ITS.Infrastructure.Helpers;
using ITS.DAL.Users;

namespace ITS.Website.Controllers
{
    //[CustomAuthorize(Roles = "Administrator")]
    public class UserController : BaseController
    {
        private readonly IUserAccountRepository _userRepository;
        public UserController(IUserAccountRepository userRepository)
        {
            this._userRepository = userRepository;
        }
        //
        // GET: /Admin/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult CreateUser()
        {
            CreateUserViewModel model = new CreateUserViewModel()
            {
                Username = String.Empty,
                Password = String.Empty,
                SelectRoleModels = new List<SelectRoleModel>()
            };
            IList<Role> roles = _userRepository.Roles.ToList();
            model.SelectRoleModels = (from r in _userRepository.Roles
                                      select new SelectRoleModel
                {
                    RoleID = r.RoleID,
                    RoleName = r.RoleName,
                    Checked = false,
                    Description = r.Description
                }).ToList();
            return View(model);
        }

        [HttpPost]
        public ActionResult CreateUser(FormCollection collection)
        {
            CreateUserViewModel model = new CreateUserViewModel();
            TryUpdateModel<CreateUserViewModel>(model);
            if (ModelState.IsValid)
            {
                if (!CheckUserAvailable(model.Username))
                {
                    ModelState.AddModelError(String.Empty, "This username is not available");
                }
                else
                {
                    User user = new User()
                    {
                        UserID = Guid.NewGuid(),
                        UserName = model.Username,
                        LastActivityDate = DateTime.Now,
                        CreateDate = DateTime.Now,
                        LastLoginDate = DateTime.Now,
                        LastPasswordChangedDate = DateTime.Now,
                        LastLockoutDate = DateTime.Now,
                        IsApproved = true,
                        Password = CryptographyHelper.ToMD5(model.Password),
                        Comment = model.Description
                    };

                    _userRepository.Save(user);

                    UserExtended userInfo = new UserExtended()
                    {
                        UserID = user.UserID,
                        DisplayName = model.DisplayName,
                        Email = model.Email,
                        Website = model.Website
                    };
                    _userRepository.SaveUserExtended(userInfo);

                    foreach (SelectRoleModel role in model.SelectRoleModels)
                    {
                        if (role.Checked)
                        {
                            user.Roles.Add(_userRepository.RoleByID(role.RoleID));
                        }
                    }
                    _userRepository.UpdateUser(user);
                    return RedirectToAction("Users", "User");
                }
            }
            return View(model);
        }
        [HttpPost]
        public ActionResult IsExisting(string username)
        {
            return Json(new { returnvalue = _userRepository.IsExisting(username) });
        }
        private bool CheckUserAvailable(string username)
        {
            return !(_userRepository.IsExisting(username));
        }
        public ActionResult Users()
        {
            IQueryable<User> users = _userRepository.Users;
            UsersModel model = new UsersModel() { Users = users.ToList() };
            return View(model);
        }

        [HttpPost]
        public ActionResult Users(FormCollection collection)
        {
            UsersModel model = new UsersModel();
            TryUpdateModel<UsersModel>(model);
            User user = _userRepository.UserByID(model.UserToDelete);
            _userRepository.Delete(user);
            return RedirectToAction("Users");
        }

        public ActionResult EditUser(Guid ID)
        {
            User user = _userRepository.UserByID(ID);
            CreateUserViewModel model = new CreateUserViewModel()
            {
                SelectRoleModels = new List<SelectRoleModel>(),
                UserID = user.UserID,
                Username = user.UserName,
                Password = user.Password,
                Description = user.Comment
            };
            IList<Role> roles = _userRepository.Roles.ToList();

            foreach (Role r in _userRepository.Roles)
            {
                model.SelectRoleModels.Add(new SelectRoleModel { RoleID = r.RoleID, RoleName = r.RoleName, Checked = _userRepository.HasRole(user.UserID, r.RoleID), Description = r.Description });
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult EditUser(FormCollection collection)
        {
            CreateUserViewModel model = new CreateUserViewModel();
            TryUpdateModel<CreateUserViewModel>(model);
            User user = _userRepository.UserByID(model.UserID);
            if (model.Password != null)
            {
                user.Password = CryptographyHelper.ToMD5(model.Password);
            }
            user.Comment = model.Description;
            foreach (SelectRoleModel role in model.SelectRoleModels)
            {
                if (role.Checked && !_userRepository.HasRole(model.UserID, role.RoleID))
                {
                    user.Roles.Add(_userRepository.RoleByID(role.RoleID));
                }
                else if (!role.Checked && _userRepository.HasRole(model.UserID, role.RoleID))
                {
                    user.Roles.Remove(_userRepository.RoleByID(role.RoleID));
                }
            }
            _userRepository.UpdateUser(user);
            return RedirectToAction("Users");
        }

        public ActionResult DeleteUser(Guid ID)
        {
            User user = _userRepository.UserByID(ID);
            CreateUserViewModel model = new CreateUserViewModel()
            {
                SelectRoleModels = new List<SelectRoleModel>(),
                UserID = user.UserID,
                Username = user.UserName,
                Password = user.Password,
                Description = user.Comment
            };
            IList<Role> roles = _userRepository.Roles.ToList();

            foreach (Role r in _userRepository.Roles)
            {
                model.SelectRoleModels.Add(new SelectRoleModel { RoleID = r.RoleID, RoleName = r.RoleName, Checked = _userRepository.HasRole(user.UserID, r.RoleID), Description = r.Description });
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult DeleteUser(FormCollection collection)
        {
            CreateUserViewModel model = new CreateUserViewModel();
            TryUpdateModel<CreateUserViewModel>(model);
            User user = _userRepository.UserByID(model.UserID);
            _userRepository.Delete(user);
            return RedirectToAction("Users");
        }
    }
}
